﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using DevComponents.DotNetBar;
using OfficeOpenXml;
using Platform.Model;
using PlatformManagement.Properties;

namespace PlatformManagement
{
    public partial class DailyOrderForm : DevComponents.DotNetBar.Metro.MetroForm
    {
        private List<ViewPickingList> _lstViewPickingList = new List<ViewPickingList>();
        private List<Supplier> _lstSupplier = new List<Supplier>();
        private List<Article> _lstArticle = new List<Article>();
        private List<Store> _lstStore = new List<Store>();
        private List<DailyOrder> _latestOrder = new List<DailyOrder>(); 

        public DailyOrderForm()
        {
            InitializeComponent();
            dgPickingList.AutoGenerateColumns = false;
            dgArticle.AutoGenerateColumns = false;
            dgStore.AutoGenerateColumns = false;
            dgSupplier.AutoGenerateColumns = false;
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDlg.ShowDialog() == DialogResult.OK)
            {
                txtFileName.Text = openFileDlg.FileName;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (txtFileName.Text.Trim() == "")
            {
                MessageBox.Show("Please input filename");
            }
            else
            {
                try
                {
                    var fileName = txtFileName.Text;
                    const int startRow = 1;
                    var poNo = "";
                    var supNo = "";
                    var supName = "";
                    var orderDate = DateTime.Now;
                    var delDateWH = DateTime.Now;
                    var wh = 79;

                    // Khai báo file cần import
                    var existingFile = new FileInfo(fileName);
                    // Đọc file xlsx
                    using (var package = new ExcelPackage(existingFile))
                    {
                        // Đọc workbook
                        ExcelWorkbook workBook = package.Workbook;
                        if (workBook != null)
                        {
                            if (workBook.Worksheets.Count > 0)
                            {
                                // Đọc worksheet
                                ExcelWorksheet currentWorksheet = workBook.Worksheets.First();


                                for (int rowNumber = startRow + 1;
                                     rowNumber <= currentWorksheet.Dimension.End.Row;
                                     rowNumber++)
                                    // Đọc từng dòng trong worksheet bắt đầu từ (start row + 1 header row) đến dòng cuối cùng
                                {
                                    // nếu dòng thông tin DailyOrder có giá trị, lưu lại thông tin DailyOrder
                                    if (currentWorksheet.Cells[rowNumber, 2].Value != null)
                                    {
                                        wh = int.Parse(currentWorksheet.Cells[rowNumber, 1].Value == null
                                                           ? "79"
                                                           : currentWorksheet.Cells[rowNumber, 1].Value
                                                                                                 .ToString());
                                        poNo = currentWorksheet.Cells[rowNumber, 2].Value.ToString();
                                        supNo = currentWorksheet.Cells[rowNumber, 3].Value.ToString();
                                        supName = currentWorksheet.Cells[rowNumber, 4].Value.ToString();
                                        orderDate = DateTime.ParseExact(
                                            currentWorksheet.Cells[rowNumber, 5].Value.ToString(),
                                            "d-M-yyyy", CultureInfo.InvariantCulture);
                                        delDateWH = DateTime.ParseExact(
                                            currentWorksheet.Cells[rowNumber, 6].Value.ToString(),
                                            "d-M-yyyy", CultureInfo.InvariantCulture);
                                    }
                                    else
                                    {
                                        // nếu dòng thông tin Picking Order có giá trị, lưu lại thông tin Picking Order với thông tin
                                        // Daily Order đã lưu gần nhất.
                                        if (currentWorksheet.Cells[rowNumber, 7].Value != null)
                                            _lstViewPickingList.Add(new ViewPickingList()
                                                {
                                                    WH = wh,
                                                    PoNo = poNo,
                                                    SupNo = supNo,
                                                    SupName = supName,
                                                    OrderDate = orderDate,
                                                    DeliDateWH = delDateWH,
                                                    StoreNo = currentWorksheet.Cells[rowNumber, 7].Value.ToString(),
                                                    OrderQty =
                                                        float.Parse(
                                                            currentWorksheet.Cells[rowNumber, 8].Value.ToString()),
                                                    OrderNo = currentWorksheet.Cells[rowNumber, 9].Value.ToString(),
                                                    ArtNo = currentWorksheet.Cells[rowNumber, 10].Value.ToString(),
                                                    ArtName = currentWorksheet.Cells[rowNumber, 11].Value.ToString(),
                                                    DeliDateST = DateTime.ParseExact(
                                                        currentWorksheet.Cells[rowNumber, 12].Value.ToString(),
                                                        "d-M-yyyy", CultureInfo.InvariantCulture),
                                                });
                                    }
                                }

                                // lấy ra danh sách nhà cung cấp từ danh sách đặt hàng
                                _lstSupplier = _lstViewPickingList
                                    .GroupBy(x => new {x.SupNo, x.SupName})
                                    .Select(x => new Supplier()
                                        {
                                            SupNo = x.Key.SupNo,
                                            LastName = x.Key.SupName.Trim().Split(' ').Last(),
                                            FirstName = x.Key.SupName.Trim().Remove(
                                                x.Key.SupName.Length -
                                                x.Key.SupName.Trim().Split(' ').Last().Length,
                                                x.Key.SupName.Trim().Split(' ').Last().Length)
                                        }).ToList();

                                // lấy ra danh sách mặt hàng từ danh sách đặt hàng
                                _lstArticle = _lstViewPickingList
                                    .GroupBy(x => new {x.ArtNo, x.ArtName})
                                    .Select(x => new Article()
                                        {
                                            ArtNo = x.Key.ArtNo,
                                            ArtName = x.Key.ArtName,
                                        }).ToList();

                                // lấy ra danh sách kho từ danh sách đặt hàng
                                var storages = WorkContext.Current.Storages.ToList();

                                _lstStore = _lstViewPickingList
                                    .GroupBy(x => x.StoreNo).Select(x =>
                                        {
                                            var s = storages.FirstOrDefault(_ => _.StoreNo == x.Key);
                                            return s != null
                                                       ? new Store()
                                                           {
                                                               StoreNo = x.Key,
                                                               StoreName = s.StoreName,
                                                           }
                                                       : null;
                                        }).ToList();

                                dgPickingList.DataSource = _lstViewPickingList;
                                dgSupplier.DataSource = _lstSupplier;
                                dgArticle.DataSource = _lstArticle;
                                dgStore.DataSource = _lstStore;
                            }
                        }
                    }

                }
                catch (IOException ioEx)
                {
                    if (!String.IsNullOrEmpty(ioEx.Message))
                    {
                        if (ioEx.Message.Contains("because it is being used by another process."))
                        {
                            MessageBox.Show("Could not read example data. Please make sure it not open in Excel.");
                        }
                    }
                    MessageBox.Show("Could not read example data. " + ioEx.Message);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occured while reading example data. " + ex.Message);
                }
            }
        }

        /// <summary>
        /// Xử lý sự kiện lưu dữ liệu đã import từ file excel vào database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            Supplier sup;
            Article art;
            DailyOrder dailyOrder;
            var pickingList = new List<PickingList>();
            var lastDoId = 0;

            // lấy danh sách Daily Order đã có trong ngày
            var dailyOrders =
                DailyOrder.Objects.Where(
                    x => x.LastUpdated.Date == DateTime.Now.Date && x.MarketId == WorkSession.Current.Market.ID)
                          .ToList();

            if (MessageBox.Show(
                    Resources.DailyOrderForm_btnSave_Click_AskForSaveMissingData,
                    Resources.MainForm_Title, MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    foreach (var p in _lstViewPickingList)
                    {
                        // kiểm tra nếu nhà cung cấp chưa có thì thêm nhà cung cấp
                        if (WorkContext.Current.Suppliers.GetProvider(p.SupNo) == null)
                        {
                            sup = new Supplier()
                            {
                                SupNo = p.SupNo,
                                LastName = p.SupName.Trim().Split(' ').Last(),
                                FirstName =
                                    p.SupName.Trim()
                                     .Remove(p.SupName.Length - p.SupName.Trim().Split(' ').Last().Length,
                                             p.SupName.Trim().Split(' ').Last().Length),
                                MarketId = WorkSession.Current.Market.ID,
                                LastUpdated = DateTime.Now
                            };
                            p.SupId = WorkContext.Current.Suppliers.AddOrUpdate(sup);
                        }

                        // kiểm tra nếu mặt hàng chưa có thì thêm mặt hàng
                        if (WorkContext.Current.Articles.GetArticle(p.ArtNo) == null)
                        {
                            art = new Article()
                            {
                                ArtNo = p.ArtNo,
                                ArtName = p.ArtName,
                                MarketId = WorkSession.Current.Market.ID,
                                LastUpdated = DateTime.Now
                            };

                            p.ArtId = WorkContext.Current.Articles.AddOrUpdate(art);
                        }

                        // kiểm tra nếu chưa có đơn đặt hàng thì thêm đơn đặt hàng
                        if (dailyOrders.FirstOrDefault(x => x.PoNo == p.PoNo) == null)
                        {
                            dailyOrder = new DailyOrder()
                            {
                                WH = p.WH.ToString(),
                                PoNo = p.PoNo,
                                MarketId = WorkSession.Current.Market.ID,
                                SupId = p.SupId != 0 ? p.SupId : WorkContext.Current.Suppliers.GetProviderId(p.SupNo),
                                OrderDate = p.OrderDate,
                                DeliDateST = p.DeliDateST,
                                DeliDateWH = p.DeliDateWH,
                                LastUpdated = DateTime.Now
                            };
                            dailyOrder.Insert(true);
                            dailyOrders.Add(dailyOrder);
                            p.DoId = dailyOrder.Id;
                            lastDoId = p.DoId;
                        }
                        else
                        {
                            p.DoId = lastDoId;
                        }

                        // tạo PickingList
                        pickingList.Add(new PickingList()
                        {
                            DoId = p.DoId,
                            StoreId = WorkContext.Current.Storages.GetStoreId(p.StoreNo),
                            OrderNo = p.OrderNo,
                            ArtId = p.ArtId != 0 ? p.ArtId : WorkContext.Current.Articles.GetArticleId(p.ArtNo),
                            OrderQty = p.OrderQty,
                            Status = false,
                            LastUpdated = DateTime.Now
                        });
                    }
                    // batch insert
                    PickingList.Objects.Insert(pickingList);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                
            }
        }

        private void dgStore_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgStore.Rows[e.RowIndex].Cells[0].Value != null)
            {
                var lst = _lstViewPickingList
                    .Where(x => x.StoreNo == dgStore.Rows[e.RowIndex].Cells[0].Value.ToString()).ToList();
                dgPickingList.DataSource = lst;
            }
        }

        private void dgArticle_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgArticle.Rows[e.RowIndex].Cells[0].Value != null)
            {
                var lst = _lstViewPickingList
                    .Where(x => x.ArtNo == dgArticle.Rows[e.RowIndex].Cells[0].Value.ToString()).ToList();
                dgPickingList.DataSource = lst;
            }
        }

        private void dgSupplier_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgSupplier.Rows[e.RowIndex].Cells[0].Value != null)
            {
                var lst = _lstViewPickingList
                    .Where(x => x.SupNo == dgSupplier.Rows[e.RowIndex].Cells[0].Value.ToString()).ToList();
                dgPickingList.DataSource = lst;
            }
        }

       

    }
}